<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Serialization demo</title>

  <link rel="stylesheet" href="demo.css"/>

  <script src="../src/jquery.js"></script>
  <script src="../src/gridstack.js"></script>
  <script src="../src/jquery-ui.js"></script>
  <script src="../src/gridstack.jQueryUI.js"></script>
</head>
<body>
  <div class="container-fluid">
    <h1>Serialization demo</h1>
    <a onClick="saveGrid()" class="btn btn-primary" href="#">Save</a>
    <a onClick="loadGrid()" class="btn btn-primary" href="#">Load</a>
    <a onClick="clearGrid()" class="btn btn-primary" href="#">Clear</a>
    <br/><br/>
    <div class="grid-stack"></div>
    <hr/>
    <textarea id="saved-data" cols="100" rows="20" readonly="readonly"></textarea>
  </div>

  <script type="text/javascript">
    var grid = GridStack.init();
    
    grid.on('added removed change', function(e, items) {
      var str = '';
      items.forEach(function(item) { str += ' (x,y)=' + item.x + ',' + item.y; });
      console.log(e.type + ' ' + items.length + ' items:' + str );
    });

    var serializedData = [
      {x: 0, y: 0, width: 2, height: 2},
      {x: 3, y: 1, width: 1, height: 2},
      {x: 4, y: 1, width: 1, height: 1},
      {x: 2, y: 3, width: 3, height: 1},
      {x: 1, y: 3, width: 1, height: 1}
    ];

    loadGrid = function() {
      grid.removeAll();
      var items = GridStack.Utils.sort(serializedData);
      grid.batchUpdate();
      items.forEach(function (node) {
        grid.addWidget('<div><div class="grid-stack-item-content"></div></div>', node);
      });
      grid.commit();
    };

    saveGrid = function() {
      serializedData = [];
      grid.engine.nodes.forEach(function(node) {
        serializedData.push({
          x: node.x,
          y: node.y,
          width: node.width,
          height: node.height
        });
      });
      document.querySelector('#saved-data').value = JSON.stringify(serializedData, null, '  ');
    };

    clearGrid = function() {
      grid.removeAll();
    }

    loadGrid();
  </script>
</body>
</html>
